<?php

namespace App\Kuafu\WaiMai\Model;

use App\Kuafu\Base\Model\Traits\KfSplitRelation;
use App\Kuafu\Base\Model\Traits\KfWaiMaiSplit;
use App\Kuafu\Order\Service\OrderDb;
use App\Library\SnowFlake\SnowFlake;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Kuafu\Base\Model\BaseModel;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

class WaiMaiOrderDetailModel extends BaseModel
{
    use HasFactory;
    use KfWaiMaiSplit;
    use KfSplitRelation;

    protected $connection = 'mysqlWaiMai';
    protected $table      = 'waimai_order_details'; //表名
    protected $primaryKey = 'id';
    protected $fillable   = [
        'shopId',
        'brandId',
        'orderId',
        'productName',
        'productProperty',
        'unit',
        'originUnitPrice',
        'num',
        'payPrice',
        'originalPrice',
        'discountPrice',
        'productType',
        'uniqueId',
        'skuId',
        'partRefundNum',
        'createdAt',
        'updatedAt',
        'commodities',
        'productNameStandard',
    ];

    const PRODUCT_TYPE_1 = 1; // 菜
    const PRODUCT_TYPE_2 = 2; // 餐盒费

    const PRODUCT_TYPE_2_TEXT = '餐盒费';

    // 仅关联菜品，不关联包装物
    public function orderRel(): HasOne
    {
        $tableName = (new WaiMaiOrderModel)->getBaseTable();
        $connect   = OrderDb::orderDbConnection(self::$splitShopId, OrderDb::DB_TYPE_WAIMAI);

        return $this->hasOneWithTable(WaiMaiOrderDetailModel::class, 'orderId', 'orderId', $tableName, $connect);
    }

    public static function addData(array $data)
    {
        $data = array_map(function($item) {
            $item['id'] = SnowFlake::nextIdCache();
            return $item;
        }, $data);

        return self::suffix($data[0]['shopId'])->insert($data);
    }

    /**
     * 操作部分退款
     * @param int $shopId
     * @param int $orderId
     * @param Collection $foodArr
     * @param bool $agree true:同意 false:拒绝
     */
    public static function partRefund(int $shopId, int $orderId, Collection $foodArr, bool $agree = true): void
    {
        $foodArr->each(function ($item) use ($orderId, $shopId, $agree) {

            // 先用skuId匹配菜品
            $detail = WaiMaiOrderDetailModel::suffix($shopId)
                                  ->where('orderId', $orderId)
                                  ->where('skuId', $item['skuId'])
                                  ->orderByDesc('num')
                                  ->first();

            // 如果是老数据，没有skuId就用name匹配
            if (!$detail) {
                $detail = WaiMaiOrderDetailModel::suffix($shopId)
                                                ->where('orderId', $orderId)
                                                ->where('productName', $item['name'])
                                                ->orderByDesc('num')
                                                ->first();
            }

            // TODO 该报警了
            if (!$detail) {
                Log::warning("partRefund db error; shopId:{$shopId} orderId:{$orderId} agree:{$agree}", $item);
                return;
            }

            if ($agree) {
                $detail->partRefundNum = $item['refundNum'];
            } else {
                $detail->partRefundNum = 0;
            }
            $detail->save();
        });
    }

    /**
     * 清空订单下的partRefundNum
     * @param int $shopId
     * @param int $orderId
     * @return mixed
     */
    public static function clearPartRefundNum(int $shopId, int $orderId)
    {
        return WaiMaiOrderDetailModel::suffix($shopId)
                                     ->where('orderId', $orderId)
                                     ->where('partRefundNum', '>', 0)
                                     ->update(['partRefundNum' => 0]);
    }
}
